<template>
	<div class="w70 center">
		<!--    <el-card>-->
		<el-form size="large" ref="dicDialogFormRef" :model="dataForm" label-width="120px" :rules="dataRules" v-loading="loading">
			<el-col :span="24" class="mb20">
				<el-form-item label="社保卡" prop="medicalCard">
					<el-input v-model="dataForm.medicalCard" clearable placeholder="输入社保卡">
						<template #append>
							<el-button-group>
								<el-button type="primary" @click="readCard">读卡</el-button>
								<el-button plain @click="restData">清空</el-button>
							</el-button-group>
						</template>
					</el-input>
				</el-form-item>
			</el-col>

			<el-row>
				<el-col :span="12" class="mb20">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="dataForm.name" autocomplete="off" placeholder="请输入姓名">
							<template #append>
								<el-popover placement="bottom" :width="700" trigger="click" ref="popoverRef">
									<template #reference>
										<el-button type="primary" @click="searchData" v-auth="'name_query'">查询</el-button>
									</template>
									<div>
										<el-form-item label="姓名：" label-width="60" style="text-align: left">
											<el-input v-model="userName" @input="inputName" autocomplete="off" placeholder="请输入姓名"> </el-input>
										</el-form-item>
									</div>
									<el-table :data="gridData" height="300" @row-dblclick="dbclick">
										<el-table-column width="120" property="name" label="姓名" show-overflow-tooltip />
										<el-table-column width="60" property="age" label="年龄" show-overflow-tooltip />
										<el-table-column width="80" property="sex" label="性别" show-overflow-tooltip>
											<template #default="scope">
												<el-tag size="small" v-if="scope.row.sex === '1'">男</el-tag>
												<el-tag size="small" v-if="scope.row.sex === '2'">女</el-tag>
											</template>
										</el-table-column>
										<el-table-column width="180" property="icCard" label="身份证号" show-overflow-tooltip />
										<el-table-column width="120" property="villageName" label="村" show-overflow-tooltip />
										<el-table-column width="" property="address" label="家庭地址" show-overflow-tooltip />
									</el-table>
								</el-popover>
							</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="出生日期" prop="birthday">
						<!--            <el-input v-model="dataForm.birthday" clearable disabled></el-input>-->
						{{ dataForm.birthday?.substring(0, 10) }}
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="12" class="mb20">
					<el-form-item label="体检编号" prop="examId">
						<el-input v-model="dataForm.examNo" clearable disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="标签序号" prop="medicalCard">
						<el-input v-model="dataForm.labelNo" clearable disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="12" class="mb20">
					<el-form-item label="性别" prop="sex">
						<template v-for="(item, index) in gender">
							<el-tag v-if="dataForm.sex == item.value" :key="index">{{ item.label }}</el-tag>
						</template>

						<!--            <el-radio-group v-model="dataForm.sex" disabled>-->
						<!--              <el-radio :label="item.value" v-for="(item, index) in gender" border :key="index">{{-->
						<!--                  item.label-->
						<!--                }}-->
						<!--              </el-radio>-->
						<!--            </el-radio-group>-->
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="年龄" prop="age">
						<el-input v-model="dataForm.age" clearable disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="12" class="mb20">
					<el-form-item label="联系电话" prop="tel">
						<el-input v-model="dataForm.tel" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="管理状态" prop="healthStatus">
						<template v-for="(item, index) in bloodx_health">
							<el-tag v-if="dataForm.healthStatus == item.value" :key="index">{{ item.label }}</el-tag>
						</template>
						<!--            <el-radio-group v-model="dataForm.healthStatus" disabled>-->
						<!--              <el-radio :label="item.value" v-for="(item, index) in bloodx_health" border :key="index">{{-->
						<!--                  item.label-->
						<!--                }}-->
						<!--              </el-radio>-->
						<!--            </el-radio-group>-->
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="12" class="mb20">
					<el-form-item label="村" prop="village">
						<el-select v-model="dataForm.village" disabled>
							<el-option :label="item.name" :value="item.id" v-for="(item, index) in village" :key="index" />
						</el-select>
						<!--            <el-input v-model="dataForm.villageName" disabled></el-input>-->
						<!--            <el-select v-model="dataForm.village" disabled>-->
						<!--              <el-option :label="item.label" :value="item.value" v-for="(item, index) in village"-->
						<!--                         :key="index"/>-->
						<!--            </el-select>-->
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="家庭医生" prop="familyDoctor">
						<el-select v-model="dataForm.familyDoctor" disabled>
							<el-option :key="item.userId" :label="item.name" :value="item.userId" v-for="item in doctorList" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24" class="mb20">
					<el-form-item label="地址" prop="address">
						{{ dataForm.address }}
						<!--            <el-input type="textarea" v-model="dataForm.address" disabled/>-->
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8" class="mb20">
					<el-form-item label="体检日期" prop="address">
						{{ examTime }}
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<el-form-item label="打印张数" prop="sheetsNumber">
						<el-input v-model="dataForm.sheetsNumber" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<el-form-item label="签到状态" prop="signStatus">
						<el-tag v-if="dataForm.signStatus == '1'" type="success">已签到</el-tag>
						<el-tag v-else type="danger">未签到</el-tag>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24" class="mb20">
					<el-form-item>
						<el-button type="danger" icon="CloseBold" @click="cancel">取消签到</el-button>
						<el-button type="success" @click="onSubmit" icon="Select">确认签到</el-button>
						<el-button type="primary" icon="Printer" @click="print">打印标签</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<!--    </el-card>-->
	</div>
</template>
<script setup lang="ts" name="exam-form">
import { signById, getTime } from '/@/api/blood/bloodxExamCustomer';
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
// import {readCardDevice} from '/@/utils/ajaxUtil';
// import { fetchList } from '/@/api/blood/bloodxCustomer';
// import {fetchList} from '/@/api/blood/bloodxExamCustomer';
import { getCustomerByMedicalCard, getCustomerByName } from '/@/api/blood/bloodxExam';
import { getDoctorList } from '/@/api/information/village';
import { sysVillageList } from '/@/api/blood/bloodxCustomer';
import { ref } from 'vue';
// 定义字典
const { gender, bloodx_health } = useDict('gender', 'bloodx_health');

const loading = ref(false);
const dicDialogFormRef = ref();
const doctorList = ref<any[]>([]);
const village = ref([]);
const popoverRef = ref(null);

const userName = ref('');
const gridData = ref([]);
const inputTimer = ref(null);

// 接收组件传输的接收表单
const dataForm = reactive({
	examId: '',
	examNo: '',
	labelNo: '',
	id: '',
	name: '',
	birthday: '',
	age: null,
	sex: '',
	icCard: '',
	tel: '',
	address: '',
	village: '',
	localCard: '',
	medicalCard: '',
	healthStatus: '',
	familyDoctor: '',
	updateTime: '',
	sexname: '',
	villageName: '',
	allCustomer: '',
	allSignCustomer: '',
	signStatus: '',
	sheetsNumber: '',
});
const dataRules = reactive({});
const examTime = ref('');
const readCardWs = ref(null);
onMounted(() => {
	getdoctorList();
	getExamTime();
});

const searchData = () => {
	gridData.value = [];
	userName.value = '';
	if (dataForm.name) {
		userName.value = dataForm.name;
		inputName(userName.value);
	}
};

onBeforeUnmount(() => {
	if (inputTimer.value) {
		clearTimeout(inputTimer.value);
	}
});

const inputName = (val: string) => {
	if (inputTimer.value) {
		clearTimeout(inputTimer.value);
	}

	if (val === '') {
		gridData.value = [];
		return;
	}
	const data = {
		name: userName.value,
	};
	inputTimer.value = setTimeout(() => {
		getCustomerByName(data).then((res) => {
			if (res.data.length === 0) {
				gridData.value = [];
				return;
			}
			gridData.value = res.data;
		});
	}, 500);
};

const dbclick = (row: any) => {
	dataForm.id = row.id;
	dataForm.examNo = row.examNo;
	dataForm.medicalCard = row.medicalCard;
	dataForm.name = row.name;
	dataForm.birthday = row.birthday;
	dataForm.sex = row.sex;
	dataForm.age = row.age;
	dataForm.healthStatus = row.healthStatus;
	dataForm.village = row.village;
	dataForm.villageName = row.villageName;
	dataForm.familyDoctor = row.familyDoctor;
	dataForm.address = row.address;
	dataForm.sex = row.sex;
	dataForm.tel = row.tel;
	dataForm.examId = row.examId;
	dataForm.labelNo = row.labelNo;
	dataForm.updateTime = row.updateTime;
	dataForm.sexname = row.sex == '1' ? '男' : '女';
	dataForm.icCard = row.icCard;
	dataForm.allCustomer = row.allCustomer;
	dataForm.allSignCustomer = row.allSignCustomer;
	dataForm.signStatus = row.signStatus;
	dataForm.sheetsNumber = row.sheetsNumber;
	popoverRef.value.hide();
};

const getdoctorList = () => {
	getDoctorList().then((res) => {
		doctorList.value = res.data;
	});
	sysVillageList().then((res) => {
		village.value = res.data;
	});
};
const getExamTime = () => {
	getTime().then((res) => {
		examTime.value = res.data;
	});
};

const restData = () => {
	dataForm.examId = '';
	dataForm.examNo = '';
	dataForm.labelNo = '';
	dataForm.id = '';
	dataForm.name = '';
	dataForm.birthday = '';
	dataForm.age = '';
	dataForm.sex = '';
	dataForm.icCard = '';
	dataForm.tel = '';
	dataForm.address = '';
	dataForm.village = '';
	dataForm.localCard = '';
	dataForm.medicalCard = '';
	dataForm.healthStatus = '';
	dataForm.familyDoctor = '';
	dataForm.updateTime = '';
	dataForm.sexname = '';
	dataForm.villageName = '';
	dataForm.allCustomer = '';
	dataForm.allSignCustomer = '';
	dataForm.signStatus = '';
};

const getExamCustomer = () => {
	getCustomerByMedicalCard({
		medicalCard: dataForm.medicalCard,
	})
		.then((res) => {
			if (res.data.id === null) {
				useMessage().error('暂无数据');
			}
			if (res.data.id === undefined) {
				useMessage().error(res.data);
			}
			dataForm.id = res.data.id;
			dataForm.examNo = res.data.examNo;
			dataForm.medicalCard = res.data.medicalCard;
			dataForm.name = res.data.name;
			dataForm.birthday = res.data.birthday;
			dataForm.sex = res.data.sex;
			dataForm.age = res.data.age;
			dataForm.healthStatus = res.data.healthStatus;
			dataForm.village = res.data.village;
			dataForm.villageName = res.data.villageName;
			dataForm.familyDoctor = res.data.familyDoctor;
			dataForm.address = res.data.address;
			dataForm.sex = res.data.sex;
			dataForm.tel = res.data.tel;
			dataForm.examId = res.data.examId;
			dataForm.labelNo = res.data.labelNo;
			dataForm.updateTime = res.data.updateTime;
			dataForm.sexname = res.data.sex == '1' ? '男' : '女';
			dataForm.icCard = res.data.icCard;
			dataForm.allCustomer = res.data.allCustomer;
			dataForm.allSignCustomer = res.data.allSignCustomer;
			dataForm.signStatus = res.data.signStatus;
			dataForm.sheetsNumber = res.data.sheetsNumber;
		})
		.catch((err) => {
			useMessage().error(err.msg);
		});
};

const readCard = async () => {
	// 清空表单
	dataForm.examNo = '';
	dataForm.labelNo = '';
	dataForm.id = '';
	dataForm.name = '';
	dataForm.birthday = '';
	dataForm.age = null;
	dataForm.sex = '';
	dataForm.icCard = '';
	dataForm.tel = '';
	dataForm.address = '';
	dataForm.village = '';
	dataForm.localCard = '';
	dataForm.healthStatus = '';
	dataForm.familyDoctor = '';
	dataForm.updateTime = '';
	dataForm.sexname = '';
	dataForm.villageName = '';
	dataForm.sheetsNumber = '0';
	dataForm.allCustomer = '';
	dataForm.allSignCustomer = '';
	dataForm.signStatus = '';

	loading.value = true;
	try {
		if (dataForm.medicalCard != '' && dataForm.medicalCard != null) {
			getExamCustomer();
		} else {
			sendReadCard('ws://127.0.0.1:2018', (message) => {
				if (!JSON.parse(message).Data.IsSuccess) {
					useMessage().error('读卡失败，请重新读卡');
					return;
				}
				useMessage().success('读卡成功');
				let list = JSON.parse(message).Data.kh.split('|');
				dataForm.medicalCard = list[2];
				getExamCustomer();
			});
		}
	} finally {
		loading.value = false;
	}
};
const sendReadCard = (WSURL: any, callback: any) => {
	if (readCardWs.value !== null) {
		if (readCardWs.value.readyState === 0 || readCardWs.value.readyState === 1) {
			return;
		} else {
			readCardWs.value.close();
		}
	}
	readCardWs.value = new WebSocket(WSURL);
	readCardWs.value.addEventListener('open', () => {
		readCardWs.value.send('读卡');
	});

	readCardWs.value.addEventListener('close', () => {});

	readCardWs.value.addEventListener('error', () => {
		readCardWs.value.close();
		useMessage().error('读卡失败');
	});

	readCardWs.value.addEventListener('message', (message) => {
		if (message.data !== 'Open!') {
			readCardWs.value.close();
			callback(message.data);
		}
	});
};

const print = () => {
	if (dataForm.labelNo) {
		for (let i = 0; i < Number(dataForm.sheetsNumber); i++) {
			printlist(
				'ws://127.0.0.1:2018',
				JSON.stringify({
					ParamTemplateName: 'xtbq.frx',
					Param1: dataForm.allSignCustomer + '/' + dataForm.allCustomer,
					Param2: dataForm.villageName,
					Param3: dataForm.name,
					Param4: dataForm.sexname + '性',
					Param5: dataForm.age + '岁',
					Param6: dataForm.icCard,
					Param7: examTime.value,
					Param8: dataForm.labelNo,
				})
			);
		}
		setTimeout(() => {
			restData();
		}, 1000);
	} else {
		useMessage().error('请先签到');
	}
};

function printlist(WSURL, str) {
	let ws = new WebSocket(WSURL);
	ws.addEventListener('open', () => {
		ws.send(str);
		ws.close();
	});

	ws.addEventListener('close', () => {});

	ws.addEventListener('error', () => {
		ws.close();
		useMessage().error('请检查打印服务是否开启');
	});

	ws.addEventListener('message', () => {});
}

const cancel = () => {
	sign(0);
};

const onSubmit = () => {
	sign(1);
};

// 签到
const sign = async (type: any) => {
	if (!dataForm.id) {
		useMessage().error('请先读卡');
		return;
	}
	await signById(
		Object.assign({
			examId: dataForm.examId,
			id: dataForm.id,
			bloodxExamTime: '',
			signStatus: type,
		})
	)
		.then((res) => {
			dataForm.labelNo = res.data.labelNo;
			dataForm.villageName = res.data.villageName;
			dataForm.allSignCustomer = res.data.allSignCustomer;
			dataForm.allCustomer = res.data.allCustomer;
			dataForm.signStatus = res.data.signStatus;
			type == 1 ? useMessage().success('签到成功') : useMessage().success('取消签到');
		})
		.catch((res) => {
			useMessage().error(res.msg);
		});
};
</script>

<style scoped>
:deep(.el-input.is-disabled .el-input__inner) {
	color: var(--el-input-text-color, var(--el-text-color-regular));
	-webkit-text-fill-color: var(--el-input-text-color, var(--el-text-color-regular));
}

.radius {
	border: 1px solid var(--el-border-color);
	margin-top: 20px;
	border-radius: 4px;
}

.el-input-group__append button.el-button:first-child {
	border-top-left-radius: 0;
	border-bottom-left-radius: 0;
	border-color: var(--el-color-primary);
	background-color: var(--el-color-primary);
	color: var(--el-color-white);
}
</style>
